﻿using System;
using System.Linq;
using SDF.Core;
using SDF.Core.Domain.Projects;
using SDF.Services.Projects;

namespace SDF.Web.Framework
{
    /// <summary>
    /// Project context for web application
    /// </summary>
    public partial class WebProjectContext : IProjectContext
    {
        private readonly IProjectService _projectService;
        private readonly IWebHelper _webHelper;

        private Project _cachedProject;

        public WebProjectContext(IProjectService projectService, IWebHelper webHelper)
        {
            this._projectService = projectService;
            this._webHelper = webHelper;
        }

        /// <summary>
        /// Gets or sets the current project
        /// </summary>
        public virtual Project CurrentProject
        {
            get
            {
                if (_cachedProject != null)
                    return _cachedProject;

                //ty to determine the current project by HTTP_HOST
                var host = _webHelper.ServerVariables("HTTP_HOST");
                var allProjects = _projectService.GetAllProjects();
                var project = allProjects.FirstOrDefault(s => s.ContainsHostValue(host));

                if (project == null)
                {
                    //load the first found project
                    project = allProjects.FirstOrDefault();
                }
                if (project == null)
                    throw new Exception("No project could be loaded");

                _cachedProject = project;
                return _cachedProject;
            }
        }
    }
}
